package boncoin.handler;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import boncoin.Annonce;

public class ImagesAnnonceHandler extends DefaultHandler
{
	public static String IMG_QNAME = "img";
	public static String DIV_QNAME = "div";
	
	private Annonce currentAnnonce = null;

	private boolean startImageDiv = false;

	public ImagesAnnonceHandler(Annonce annonce)
	{
		this.currentAnnonce = annonce;
	}
	
	public void startDocument() throws SAXException
	{
		super.startDocument();
	}
	
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException
	{
		super.startElement(uri, localName, qName, attributes);
		
		if( IMG_QNAME.equals(qName))
		{
			if(startImageDiv)
			{
				String urlImage = attributes.getValue("src");
				
				currentAnnonce.addImageUrl(urlImage);
			}
		}
		if (DIV_QNAME.equals(qName))
		{
			String clazz = attributes.getValue("class");
			if( "print-image-other".equals(clazz))
				startImageDiv = true;
		}
	}
	
	public void characters(char[] ch, int start, int length)
			throws SAXException
	{
		super.characters(ch, start, length);
		
	}

	public StringBuffer buildString(char[] ch, int start, int length)
	{
		StringBuffer sb = new StringBuffer();
		for (int i = start; i < start + length; i++)
		{
			sb.append(ch[i]);
		}
		return sb;
	}
	
	public void endElement(String uri, String localName, String qName)
			throws SAXException
	{
		super.endElement(uri, localName, qName);
		
		if( DIV_QNAME.equals(qName))
		{
			startImageDiv = false;
		}
	}
	
	public void endDocument() throws SAXException
	{
		super.endDocument();
	}
}